/**
 * 顺序栈实现
 * 使用数组实现栈
 */
public class ArrayStack<T> implements StackInterface<T> {
    private Object[] stackArray; // 存储栈元素的数组
    private int top; // 栈顶指针（-1表示空栈）
    private int capacity; // 栈的最大容量

    /**
     * 构造方法：指定栈初始容量
     * 
     * @param capacity 初始容量
     */
    public ArrayStack(int capacity) {
        this.capacity = capacity;
        this.stackArray = new Object[capacity];
        this.top = -1; // 初始化为空栈
    }

    /**
     * 默认构造方法：容量为100
     */
    public ArrayStack() {
        this(100);
    }

    @Override
    public boolean isEmpty() {
        return top == -1;
    }

    @Override
    public boolean isFull() {
        return top == capacity - 1;
    }

    @Override
    public void push(T data) {
        if (isFull()) {
            // 扩展容量
            expandCapacity();
        }
        stackArray[++top] = data; // 栈顶指针上移后存入元素
    }

    /**
     * 扩展数组容量
     */
    private void expandCapacity() {
        int newCapacity = capacity * 2;
        Object[] newArray = new Object[newCapacity];
        System.arraycopy(stackArray, 0, newArray, 0, top + 1);
        stackArray = newArray;
        capacity = newCapacity;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空，无法执行pop操作");
        }
        return (T) stackArray[top--]; // 返回栈顶元素后指针下移
    }

    @Override
    @SuppressWarnings("unchecked")
    public T peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空，无法执行peek操作");
        }
        return (T) stackArray[top];
    }

    @Override
    public int size() {
        return top + 1;
    }

    @Override
    public void clear() {
        top = -1; // 指针重置为-1，逻辑清空栈
    }
}
